/*
========================================================================
 Name        : MMSMateContainerView.cpp
 Author      : 
 Copyright   : William Yu
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <aknviewappui.h>
#include <eikmenub.h>
#include <avkon.hrh>
#include <akncontext.h>
#include <akntitle.h>
#include <stringloader.h>
#include <barsread.h>
#include <eikbtgpc.h>
#include <gdi.h>
#include <eikedwin.h>
#include <eikenv.h>
#include <MMSMate.rsg>
// ]]] end generated region [Generated System Includes]

// [[[ begin generated region: do not modify [Generated User Includes]
#include "MMSMate.hrh"
#include "MMSMateContainerView.h"
#include "MMSMateContainer.hrh"
#include "MMSMateContainer.h"
// ]]] end generated region [Generated User Includes]

// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]
#include "MMSMateAppUi.h"
#include <MSVAPI.H>
#include <mtclreg.h>              	// for CClientMtmRegistry 
#include <msvids.h>               	// for Message type IDs
#include <mmsclient.h>            	// for CMmsClientMtm
#include <CMsvMimeHeaders.h>		//Attachemt mimeheader
#include <MMsvAttachmentManager.h>	//Attachment manager
#include <aknquerydialog.h> 
#include <charconv.h>
#include <UTF.H>

//
#include <TXTRICH.H>
#include <sendui.h> 
#include <cmessagedata.h> 
#include <SendUiConsts.h>
#include "data.h"

//Constants
const TInt KMaxAddressLength = 20;  // maximum length for a recipient address
_LIT(KFile1, "mmsexample.jpg"); 	//Attachment file name
_LIT(KFile2, "test.txt"); 	//Attachment file name

_LIT(KFileName1, "c:\\data\\mmsexample.jpg"); 	//Attachment file name
_LIT(KFileName2, "c:\\data\\test.txt"); 	//Attachment file name

extern INFO gInfo;
/**
 * First phase of Symbian two-phase construction. Should not contain any
 * code that could leave.
 */
CMMSMateContainerView::CMMSMateContainerView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	iMMSMateContainer = NULL;
	// ]]] end generated region [Generated Contents]
	//iRecipient.Copy(_L("13601930584"));//apple
//	iRecipient.Copy(_L("13601930447"));	//wiley
	}
/** 
 * The view's destructor removes the container from the control
 * stack and destroys it.
 */
CMMSMateContainerView::~CMMSMateContainerView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	delete iMMSMateContainer;
	// ]]] end generated region [Generated Contents]

	iMMSEngine.Clean();
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance then calls the second-phase constructor
 * without leaving the instance on the cleanup stack.
 * @return new instance of CMMSMateContainerView
 */
CMMSMateContainerView* CMMSMateContainerView::NewL()
	{
	CMMSMateContainerView* self = CMMSMateContainerView::NewLC();
	CleanupStack::Pop( self );
	return self;
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance, pushes it on the cleanup stack,
 * then calls the second-phase constructor.
 * @return new instance of CMMSMateContainerView
 */
CMMSMateContainerView* CMMSMateContainerView::NewLC()
	{
	CMMSMateContainerView* self = new (ELeave) CMMSMateContainerView();
	CleanupStack::PushL( self );
	self->ConstructL();
	return self;
	}


/**
 * Second-phase constructor for view.  
 * Initialize contents from resource.
 */ 
void CMMSMateContainerView::ConstructL()
	{
	// [[[ begin generated region: do not modify [Generated Code]
	BaseConstructL( R_MMSMATE_CONTAINER_MMSMATE_CONTAINER_VIEW );
	// ]]] end generated region [Generated Code]
	
	// add your own initialization code here
	iMMSEngine.Init();	
	}
	
/**
 * @return The UID for this view
 */
TUid CMMSMateContainerView::Id() const
	{
	return TUid::Uid( EMMSMateContainerViewId );
	}

/**
 * Handle a command for this view (override)
 * @param aCommand command id to be handled
 */
void CMMSMateContainerView::HandleCommandL( TInt aCommand )
	{   
	// [[[ begin generated region: do not modify [Generated Code]
	TBool commandHandled = EFalse;
	switch ( aCommand )
		{	// code to dispatch to the AknView's menu and CBA commands is generated here
		case EMMSMateContainerViewStartMenuItemCommand:
			commandHandled = HandleStartMenuItemSelectedL( aCommand );
			break;
		case EMMSMateContainerViewTestMenuItemCommand:
			commandHandled = HandleTestMenuItemSelectedL( aCommand );
			break;
		default:
			break;
		}
	
		
	if ( !commandHandled ) 
		{
	
		if ( aCommand == EAknSoftkeyExit )
			AppUi()->HandleCommandL( EEikCmdExit );
	
		}
	// ]]] end generated region [Generated Code]
	
	}

/**
 *
 * @param aPrevViewId 
 * @param aCustomMessageId 
 * @param aCustomMessage
 */
void CMMSMateContainerView::DoActivateL(
		const TVwsViewId& /*aPrevViewId*/,
		TUid /*aCustomMessageId*/,
		const TDesC8& /*aCustomMessage*/ )
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	SetupStatusPaneL();
	
	CEikButtonGroupContainer *cba = AppUi()->Cba();
	if ( cba ) 
		{
		cba->MakeVisible( EFalse );
		}
	
	if ( !iMMSMateContainer )
		{
		iMMSMateContainer = CMMSMateContainer::NewL( ClientRect(), NULL, this );
		iMMSMateContainer->SetMopParent( this );
		AppUi()->AddToStackL( *this, iMMSMateContainer );
		} 
	// ]]] end generated region [Generated Contents]
	iMMSEngine.iContainer = iMMSMateContainer;
	}

/**
 */
void CMMSMateContainerView::DoDeactivate()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	CleanupStatusPane();
	
	CEikButtonGroupContainer *cba = AppUi()->Cba();
	if ( cba ) 
		{
		cba->MakeVisible( ETrue );
		cba->DrawDeferred();
		}
	
	if (iMMSMateContainer)
		{
		AppUi()->RemoveFromViewStack( *this, iMMSMateContainer );
		delete iMMSMateContainer;
		iMMSMateContainer = NULL;
		}
	// ]]] end generated region [Generated Contents]
	
	}

// [[[ begin generated function: do not modify
void CMMSMateContainerView::SetupStatusPaneL()
	{
	// reset the context pane
	TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext );
	CEikStatusPaneBase::TPaneCapabilities subPaneContext = 
		StatusPane()->PaneCapabilities( contextPaneUid );
	if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() )
		{
		CAknContextPane* context = static_cast< CAknContextPane* > ( 
			StatusPane()->ControlL( contextPaneUid ) );
		context->SetPictureToDefaultL();
		}
	
	// setup the title pane
	TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle );
	CEikStatusPaneBase::TPaneCapabilities subPaneTitle = 
		StatusPane()->PaneCapabilities( titlePaneUid );
	if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() )
		{
		CAknTitlePane* title = static_cast< CAknTitlePane* >( 
			StatusPane()->ControlL( titlePaneUid ) );
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_MMSMATE_CONTAINER_TITLE_RESOURCE );
		title->SetFromResourceL( reader );
		CleanupStack::PopAndDestroy(); // reader internal state
		}
				
	}
// ]]] end generated function

// [[[ begin generated function: do not modify
void CMMSMateContainerView::CleanupStatusPane()
	{
	}
// ]]] end generated function

/** 
 * Handle status pane size change for this view (override)
 */
void CMMSMateContainerView::HandleStatusPaneSizeChange()
	{
	CAknView::HandleStatusPaneSizeChange();
	
	// this may fail, but we're not able to propagate exceptions here
	TInt result;
	TRAP( result, SetupStatusPaneL() ); 
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	}

/*	
void CMMSMateContainerView::PrintNotify( const TDesC& aMessage,
                                  TUint aAttributes )
{
	iMMSEngine.EchoL(aMessage);
	if(aMessage.Length()>150) return; //too long
	
	iMMSEngine.iDynamicalTxt.Copy(_L8(""));
	_LIT(MATCH1, "mo=");
	_LIT(MATCH2, "mms=");	
	_LIT(MATCH3, "txt=");
	int pos1 = aMessage.Find(MATCH1);
	int pos2 = aMessage.Find(MATCH2);
	int pos3 = aMessage.Find(MATCH3);
	int len = aMessage.Length();
		
	if(pos1 >= 0)
	{
		//1
		int tail = len+1;
		if(pos2>=0) tail = pos2;
		iMMSEngine.iRecipient.Copy(aMessage.Mid(pos1+3, tail-pos1-3-1));
//		CEikonEnv::Static()->InfoMsg(iMMSEngine.iRecipient);
		TBuf<50> mmsname;
		mmsname.Copy(_L("other"));

		//2
		tail = len+1;
		if(pos3>=0) tail = pos3;
		
		if(pos2 >= 0)
			mmsname.Copy(aMessage.Mid(pos2+4, tail-pos2-4-1));
			
		if(pos3 >= 0)
			iMMSEngine.iDynamicalTxt.Copy(aMessage.Right(len-pos3-4));
		
		//3
		{
		TBuf<256> buf;	
		buf.Copy(iMMSEngine.iDynamicalTxt);
		int pos = buf.Find(_L("|"));
		if(pos > 0)
		{
			iMMSEngine.iDynamicalTxt.Copy(buf.Left(pos));
			buf.Copy(buf.Right(buf.Length()-pos-1));
		}
		pos = buf.Find(_L("|"));
		if(pos > 0)
		{
			iMMSEngine.iDynamicalTxt2.Copy(buf.Left(pos));
			buf.Copy(buf.Right(buf.Length()-pos-1));
		}
		else
			iMMSEngine.iDynamicalTxt2.Copy(buf);
			
		pos = buf.Find(_L("|"));
		if(pos > 0)
		{
			iMMSEngine.iDynamicalTxt3.Copy(buf.Left(pos));
			buf.Copy(buf.Right(buf.Length()-pos-1));
		}
		else
			iMMSEngine.iDynamicalTxt3.Copy(buf);
		
		pos = buf.Find(_L("|"));
		if(pos > 0)
		{
			iMMSEngine.iDynamicalTxt4.Copy(buf.Left(pos));
			buf.Copy(buf.Right(buf.Length()-pos-1));
		}
		else
			iMMSEngine.iDynamicalTxt4.Copy(buf);
			
		//CEikonEnv::Static()->InfoWinL(iMMSEngine.iDynamicalTxt4, buf);//iMMSEngine.iDynamicalTxt);		
		}
		
		
//		CEikonEnv::Static()->InfoWinL(iMMSEngine.iDynamicalTxt, buf);//iMMSEngine.iDynamicalTxt);
		iMMSEngine.AddTask(iMMSEngine.iRecipient, mmsname);
	}
	if(aMessage.Find(_L("hi")) >= 0)
		iMMSEngine.SetGoodStatus();	
}

void CMMSMateContainerView::PrintNotify( const TDesC8& aMessage,
                                  TUint aAttributes )
{
}

void CMMSMateContainerView::ErrorNotify( const TDesC& aErrMessage, TInt aErrCode )
{
}


void CMMSMateContainerView::SetStatus( const TDesC& aStatus )
{
	if(aStatus == _L("sock connected"))
	{
		CCoeAppUi* appui = CEikonEnv::Static()->AppUi();
		CSocketsEngine* engine = ((CMMSMateAppUi*)appui)->iSocketsEngine;
//		engine->WriteL(_L8("hi\r\n\r\n"));
		TBuf8<100> buf;
		buf.Copy(_L8("I am "));
		buf.Append(gInfo.mobilename);
		buf.Append(_L8("\r\n\r\n"));
		
//		engine->WriteL(buf);
		
		iMMSEngine.SetGoodStatus();
		iMMSEngine.EchoL(_L("Test:Say hi"));
	}	
}
*/
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */

TBool CMMSMateContainerView::HandleStartMenuItemSelectedL( TInt aCommand )
{
	// TODO: implement selected event handler
	TBuf<100> str;
	TBuf<100> buf;
	buf.Copy(_L("Name this mobile"));
	if(!RunDataQuery1L(str, false, &buf))
		return EFalse;
	
	gInfo.mobilename.Copy(str);
	
	iMMSEngine.Connect();
	return ETrue;
}
	




/* 
-----------------------------------------------------------------------------
    CMMSExampleContainer::SendMessageL()
    Sends the message.
    Return values: ETrue or EFalse
-----------------------------------------------------------------------------
*/
void CMMSMateContainerView::CreateMyMMS()
{
	CRichText* aRichText = CRichText::NewL(iEikonEnv->SystemParaFormatLayerL(), iEikonEnv->SystemCharFormatLayerL());
	aRichText->InsertL(0,_L("test"));
	
	CSendUi* aSendUi = CSendUi::NewL();
	CMessageData*  message = CMessageData::NewLC(); 
	//message->AppendToAddressL(_L("106633556661"));
	TBuf<200> buf;
	buf.Copy(_L("doritos"));
	TPtrC sub(buf);
	message->SetSubjectL(&sub);
	message->AppendAttachmentL(KFileName1);
	message->SetBodyTextL(aRichText);
//	aSendUi->CreateAndSendMessageL( KSenduiMtmMmsUid, message, KNullUid );
	aSendUi->CreateAndSendMessageL( KSenduiMtmMmsUid, message, KNullUid, false );
	//CEikonEnv::Static()->InfoWinL(_L("mms"),_L("2"));
	
	CleanupStack::PopAndDestroy( message );
	delete aRichText;
	delete aSendUi;	
	;
}
    
/**
 *	Creates the top-level container for the view.  You may modify this method's
 *	contents and the CMMSMateContainer::NewL() signature as needed to initialize the
 *	container, but the signature for this method is fixed.
 *	@return new initialized instance of CMMSMateContainer
 */
CMMSMateContainer* CMMSMateContainerView::CreateContainerL()
	{
	return CMMSMateContainer::NewL( ClientRect(), NULL, this );
	}
			
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CMMSMateContainerView::HandleTestMenuItemSelectedL( TInt aCommand )
	{
	// TODO: implement selected event handler

//////	iMMSEngine.TestMe();
//////	return EFalse;
		
    TBuf<20> addr;

    CAknTextQueryDialog* telNumDialog = CAknTextQueryDialog::NewL(addr, CAknQueryDialog::ENoTone);

    if (!telNumDialog->ExecuteLD(R_MMSEXAMPLE_TEL_NUMBER_DIALOG))
        return EFalse;
	
	TBuf<100> str;
	TBuf<100> buf;
	buf.Copy(_L("name of mms"));
	if(!RunDataQuery1L(str, false, &buf))
		return EFalse;
	
	iMMSEngine.AddTask(addr, str);
	return ETrue;
	}
				
// [[[ begin generated function: do not modify
/**
 * Show the popup dialog for dataQuery1
 * @param aData in-out TDes data
 * @param aUseDefaults TBool use designer default editor data if ETrue
 * @param aOverridePrompt optional override prompt text
 * @return EAknSoftkeyOk (left soft key id) or 0
 */
TInt CMMSMateContainerView::RunDataQuery1L( TDes& aData, TBool aUseDefaults, const TDesC* aOverridePrompt )
	{
	if ( aUseDefaults )
		{
		HBufC* text = StringLoader::LoadLC( R_MMSMATE_CONTAINER_EDIT1 );
		aData.Copy( *text );
		CleanupStack::PopAndDestroy( text );
		}
				
	CAknTextQueryDialog* queryDialog = CAknTextQueryDialog::NewL( aData );	
	
	if ( aOverridePrompt != NULL )
		{
		CleanupStack::PushL( queryDialog );
		queryDialog->SetPromptL( *aOverridePrompt );
		CleanupStack::Pop(); // queryDialog
		}
	
	return queryDialog->ExecuteLD( R_MMSMATE_CONTAINER_DATA_QUERY1 );
	}
// ]]] end generated function

/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CMMSMateContainerView::HandleRemyMenuItemSelectedL( TInt aCommand )
	{
	// TODO: implement selected event handler
    TBuf<20> addr;

    CAknTextQueryDialog* telNumDialog = CAknTextQueryDialog::NewL(addr, CAknQueryDialog::ENoTone);

    if (!telNumDialog->ExecuteLD(R_MMSEXAMPLE_TEL_NUMBER_DIALOG))
        return EFalse;
	
	iMMSEngine.AddTask(addr, _L("remy"));
	return ETrue;
	}
				